from rest_framework import serializers
from .models import Note, Like
from user_auth.serializers import UserProfileSerializer

class NoteSerializer(serializers.ModelSerializer):
    """笔记序列化器"""
    author = UserProfileSerializer(read_only=True)
    cover_image = serializers.SerializerMethodField()
    is_liked = serializers.SerializerMethodField()
    
    class Meta:
        model = Note
        fields = [
            'id', 'title', 'content', 'cover_image', 'author', 
            'created_at', 'updated_at', 'is_public', 'likes_count', 'is_liked'
        ]
        read_only_fields = ['author', 'created_at', 'updated_at', 'likes_count', 'is_liked']
    
    def get_cover_image(self, obj):
        """获取封面图片的完整URL"""
        if obj.cover_image:
            return self.context['request'].build_absolute_uri(obj.cover_image.url)
        return None
    
    def get_is_liked(self, obj):
        """检查当前用户是否已点赞"""
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            return Like.objects.filter(user=request.user, note=obj).exists()
        return False
    
    def create(self, validated_data):
        """创建笔记"""
        validated_data['author'] = self.context['request'].user
        return super().create(validated_data)

class NoteCreateSerializer(serializers.ModelSerializer):
    """创建笔记的序列化器"""
    class Meta:
        model = Note
        fields = ['title', 'content', 'cover_image', 'is_public']
    
    def create(self, validated_data):
        """创建笔记"""
        validated_data['author'] = self.context['request'].user
        return Note.objects.create(**validated_data)

class NoteUpdateSerializer(serializers.ModelSerializer):
    """更新笔记的序列化器"""
    class Meta:
        model = Note
        fields = ['title', 'content', 'cover_image', 'is_public']
    
    def update(self, instance, validated_data):
        """更新笔记"""
        # 检查权限
        if instance.author != self.context['request'].user:
            raise serializers.ValidationError('您没有权限修改这篇笔记')
        
        return super().update(instance, validated_data)

class LikeSerializer(serializers.ModelSerializer):
    """点赞序列化器"""
    class Meta:
        model = Like
        fields = ['id', 'user', 'note', 'created_at']
        read_only_fields = ['id', 'user', 'created_at']